package com.wmwj.hxlj.mapper;

import com.wmwj.hxlj.entity.Comment;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface CommentMapper {
    // 插入一条新评论
    @Insert("INSERT INTO comments (article_id, user_id, parent_id, content, likes, created_at,reply_user_id) " +
            "VALUES (#{articleId}, #{userId}, #{parentId}, #{content}, #{likes}, #{createdAt},#{replyUserId})")
    @Options(useGeneratedKeys = true, keyProperty = "commentId")
    int insertComment(Comment comment);

    // 根据commentId删除一条评论
    @Delete("DELETE FROM comments WHERE comment_id = #{commentId}")
    int deleteCommentById(Integer commentId);

    // 更新回复数量（子评论新增时触发）
    @Update("UPDATE comments SET reply_count = reply_count + 1 WHERE comment_id = #{parentId}")
    int incrementReplyCount(Long parentId);

    // 查询评论（用于校验父评论是否存在）
    @Select("SELECT * FROM comments WHERE comment_id = #{commentId}")
    Comment selectCommentById(Long commentId);

    // 根据文章ID查询所有评论
    @Select("SELECT * FROM comments WHERE article_id = #{articleId}")
    List<Comment> selectCommentsByArticleId(Long articleId);

    // 新增方法：点赞评论
    @Update("UPDATE comments SET likes = likes + 1 WHERE comment_id = #{commentId}")
    int incrementLikes(Long commentId);

    // 根据文章ID查询所有父评论
    @Select("SELECT * FROM comments WHERE article_id = #{articleId} AND parent_id IS NULL")
    List<Comment> selectParentComments(Long articleId);

    // 根据父评论ID查询所有子评论
    @Select("SELECT * FROM comments WHERE parent_id = #{parentId}")
    List<Comment> selectChildComments(Long parentId);

    // 查询所有评论
    @Select("SELECT * FROM comments LIMIT #{pageStart}, #{pageSize}")
    List<Comment> selectAllComments(int pageStart, int pageSize);

    // 查询所有评论的总数
    @Select("SELECT COUNT(*) FROM comments")
    long countAllComments();

    // 管理员搜索评论
    @Select("SELECT * FROM comments WHERE content LIKE CONCAT('%', #{keyword}, '%') LIMIT #{pageStarts}, #{pageSize}")
    List<Comment> adminSearchComments(String keyword, int pageStarts, int pageSize);

    // 管理员搜索评论的总数
    @Select("SELECT COUNT(*) FROM comments WHERE content LIKE CONCAT('%', #{keyword}, '%')")
    long adminCountByKeyword(String keyword);
}